#include "luainterface.h"

void CLuaInterface::LuaInit()
{
	
	m_pLuaState = luaL_newstate();
	
	luaL_openlibs( m_pLuaState );
	
	Lua::SetLuaState( m_pLuaState );
	
	Log::Debug( "Lua initialized" );

}

void CLuaInterface::OpenScript( const char * file )
{
	
	int r = luaL_dofile( m_pLuaState, file );
	
	if( r == 1 )
	{
	
		Log::Debug( "ERROR loading " + std::string( file ) );
		Log::Debug( lua_tostring( m_pLuaState, -1 ) );
		
	} else
		Log::Debug( "Successfully opened lua script: " + std::string( file ) );
		
	
}

void CLuaInterface::CallLevelHook( const char * s )
{
	
	lua_getglobal( m_pLuaState, "Level" );
	
	if( !LuaNil( m_pLuaState ) )
	{
		
		lua_getfield( m_pLuaState, -1, s );
		
		if( !LuaNil( m_pLuaState ) )
		{
			
			if( lua_pcall( m_pLuaState, 0, 0, 0 ) > 0 )
			{
				
				Log::Debug( lua_tostring( m_pLuaState, -1 ) );
				lua_pop( m_pLuaState, 1 );
				
			}
			
			
		} else
			lua_pop( m_pLuaState, 1 );
		
		
	} 
	
	lua_pop( m_pLuaState, 1 );
	
}

void CLuaInterface::CallEngineHook( const char * s )
{
	
	lua_getglobal( m_pLuaState, "Base" );
	
	if( !LuaNil( m_pLuaState ) )
	{
		
		lua_getfield( m_pLuaState, -1, s );
		
		if( !LuaNil( m_pLuaState ) )
		{
			
			if( lua_pcall( m_pLuaState, 0, 0, 0 ) > 0 )
			{
				
				Log::Debug( lua_tostring( m_pLuaState, -1 ) );
				lua_pop( m_pLuaState, 1 );
				
			}
			
			
		} else
			lua_pop( m_pLuaState, 1 );
		
		
	} 
	
	lua_pop( m_pLuaState, 1 );
	
}


CLuaInterface::~CLuaInterface()
{

	if( m_pLuaState )
		lua_close( m_pLuaState );
	
}